import {
  addSysDictType,
  editSysDictType,
  selectSysDictTypeByPage,
} from '@/api/information'

import {FormInstance} from 'ant-design-vue'
import {PropType} from 'vue'
import {CoustomTableFn} from '@/components/table'
import {device_list_state} from '@/views/device/list/components'

/**字典类型 状态数据 */
interface sysdictTypes_state {
  /**弹窗 */
  modal: {
    /**弹窗 关闭*/
    visible: boolean
    /**弹窗 类型*/
    type: string
    /**弹窗 标题*/
    title: string
    /** 字典类型 弹窗 修改 数据源 */
    edit_source: SysDict.Type
  }
  table: CTable<SysDict.Type>
  search: {
    dictTypeCode: string
    dictTypeName: string
  }
}
let sysdictTypes_state = reactive<sysdictTypes_state>({
  modal: {
    visible: false,
    type: '',
    title: '',
    edit_source: {
      dictDesc: '',
      sort: '',
      createTime: '',
      status: '',
      id: 0,
      dictTypeCode: '',
      dictTypeName: '',
    },
  },
  table: {
    dataSource: [],
    loading: false,
    pagination: {
      page: 1,
      size: 20,
    },
    onPaginatiChange({page, size}) {
      let {pagination} = toRefs(device_list_state.table)
      pagination.value.page = page
      pagination.value.size = size
      getTableDatas()
    },
    total: 0,
  },
  search: {
    dictTypeCode: '',
    dictTypeName: '',
  },
})

/**获取表格数据 */
export async function getTableDatas() {
  let {
    dataSource,
    pagination,
    total: tableTotal,
  } = toRefs(sysdictTypes_state.table)
  let {search} = toRefs(sysdictTypes_state)
  let defaultData = {
    page: 1,
    size: 20,
    start: 0,
    dictTypeCode: '',
    dictTypeName: '',
  }
  Object.assign(defaultData, pagination.value, search.value)
  let res = await selectSysDictTypeByPage(defaultData).catch(err => {})
  if (!res) return
  let {list, total} = res.data
  dataSource.value = list
  tableTotal.value = total
}

/**字典类型 左侧搜索筛选 */
export const ViewLeftNav = defineComponent({
  name: 'ViewLeftNav',
  setup(props, {emit}) {
    let {search} = toRefs(sysdictTypes_state)

    const handle_dictTypeName_input_enter = () => {
      getTableDatas()
    }
    return () => (
      <div class="h-full px-4 flex justify-between items-center">
        <a-input
          placeholder="输入关键字进行过滤"
          defaultValue={search.value.dictTypeName}
          v-model={[search.value.dictTypeName, 'value']}
          onPressEnter={handle_dictTypeName_input_enter}
          allow-clear={true}
        ></a-input>
        <a-button
          class="ml-4"
          type="primary"
          onClick={handle_dictTypeName_input_enter}
        >
          查询
        </a-button>
      </div>
    )
  },
})

/**字典类型 操作栏 */
export const TypeHandleBtn = defineComponent({
  props: {
    record: {
      type: Object as PropType<SysDict.Type>,
      default: {},
    },
  },
  setup(props) {
    let {visible, title, type, edit_source} = toRefs(sysdictTypes_state.modal)
    const handle_type_edit_btn_click = () => {
      visible.value = true
      type.value = 'editType'
      title.value = '修改数据类型'
      edit_source.value = props.record
    }
    return () => (
      <div>
        <span
          class="mr-2 text-primary border-b cursor-pointer"
          onClick={handle_type_edit_btn_click}
        >
          编辑
        </span>
        <span class="mr-2 text-primary border-b cursor-pointer">删除</span>
      </div>
    )
  },
})
/**字典类型 表格 */
const CoustomTable = CoustomTableFn<SysDict.Type>()
export const TypeTable = defineComponent({
  name: 'MainViewContent',
  setup(props) {
    let {dataSource, loading, total, onPaginatiChange} = toRefs(
      sysdictTypes_state.table
    )
    let {page, size} = toRefs(sysdictTypes_state.table.pagination)

    let columns: CColumn<SysDict.Type>[] = [
      {
        title: '类型编码',
        dataIndex: 'dictTypeCode',
        width: 90,
        ellipsis: true,
      },
      {
        title: '名称',
        dataIndex: 'dictTypeName',
        resizable: true,
        width: 200,
        ellipsis: true,
      },
      {
        title: '备注',
        dataIndex: 'dictDesc',
        ellipsis: true,
      },
      {
        title: '状态',
        dataIndex: 'status',
        width: 120,
        ellipsis: true,
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        ellipsis: true,
      },
      {
        title: '操作',
        dataIndex: 'utils',
        isUtil: true,
        width: 140,
      },
    ]

    return () => (
      <CoustomTable
        dataSource={dataSource.value}
        loading={loading.value}
        rowKey="dictTypeCode"
        columns={columns}
        pagination={{
          page: page.value,
          size: size.value,
          total: total.value,
        }}
        onPaginationChange={data => onPaginatiChange.value(data)}
      >
        {{
          util: (record: SysDict.Type) => (
            <TypeHandleBtn record={record}></TypeHandleBtn>
          ),
        }}
      </CoustomTable>
    )
  },
})

/**字典类型 表单 添加用 */
const AddTypeForm = defineComponent({
  emits: ['finish'],
  setup(props, {emit}) {
    let formRef = ref<FormInstance>()
    let state = reactive<SysDict.AddTypeDataSource>({
      dictDesc: '',
      dictTypeName: '',
    })
    /**提交表单且数据验证成功后回调事件 */
    const handle_form_finish = async () => {
      console.log(state)
      try {
        await addSysDictType(state)
        returnEmit()
      } catch (err) {
        console.error(err)
      }
    }
    /** 提交表单且数据验证失败后回调事件 */
    const handle_form_finish_failed = () => {
      console.log('handle_form_finish_failed', state)
      returnEmit()
    }
    /**表单取消按钮点击 */
    const handle_form_cancel = () => {
      returnEmit()
    }
    // 清空表单 关闭外层弹框
    const returnEmit = () => {
      formRef.value?.resetFields()
      emit('finish', {visible: false})
    }
    return () => (
      <a-form
        v-model={[formRef, 'ref']}
        name="addSysdictType"
        model={state}
        label-col={{span: 4}}
        wrapper-col={{span: 16}}
        onFinish={handle_form_finish}
        onFinishFailed={handle_form_finish_failed}
      >
        <a-form-item label="类型名称" name="dictTypeName">
          <a-input v-model={[state.dictTypeName, 'value']} />
        </a-form-item>
        <a-form-item label="备注" name="dictDesc">
          <a-input v-model={[state.dictDesc, 'value']} />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" class="float-right mx-4" html-type="submit">
            提交
          </a-button>
          <a-button class="float-right mx-4" onClick={handle_form_cancel}>
            取消
          </a-button>
        </a-form-item>
      </a-form>
    )
  },
})
/**字典类型 表单 添加用 */
const EditTypeForm = defineComponent({
  emits: ['finish'],
  setup(props, {emit}) {
    let {edit_source} = toRefs(sysdictTypes_state.modal)
    let formRef = ref<FormInstance>()
    let state = reactive<SysDict.EditTypeDataSource>({
      dictDesc: edit_source.value?.dictDesc || '',
      dictTypeName: edit_source.value?.dictTypeName || '',
      dictTypeCode: edit_source.value?.dictTypeCode || '',
      sort: edit_source.value?.sort || '',
    })
    /**提交表单且数据验证成功后回调事件 */
    const handle_form_finish = async () => {
      console.log(state)
      await editSysDictType(state).catch(err => {})
      returnEmit()
    }
    /** 提交表单且数据验证失败后回调事件 */
    const handle_form_finish_failed = () => {
      console.log('handle_form_finish_failed', state)
      returnEmit()
    }
    /**表单取消按钮点击 */
    const handle_form_cancel = () => {
      returnEmit()
    }
    // 清空表单 关闭外层弹框
    const returnEmit = () => {
      formRef.value?.resetFields()
      emit('finish', {visible: false})
    }
    return () => (
      <a-form
        v-model={[formRef, 'ref']}
        name="editSysdictType"
        model={state}
        label-col={{span: 4}}
        wrapper-col={{span: 16}}
        onFinish={handle_form_finish}
        onFinishFailed={handle_form_finish_failed}
      >
        <a-form-item label="类型名称" name="dictTypeName">
          <a-input v-model={[state.dictTypeName, 'value']} />
        </a-form-item>
        <a-form-item label="备注" name="dictDesc">
          <a-input v-model={[state.dictDesc, 'value']} />
        </a-form-item>
        <a-form-item label="排序" name="sort">
          <a-input v-model={[state.sort, 'value']} />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" class="float-right mx-4" html-type="submit">
            提交
          </a-button>
          <a-button class="float-right mx-4" onClick={handle_form_cancel}>
            取消
          </a-button>
        </a-form-item>
      </a-form>
    )
  },
})

/**字典类型 弹窗 */
export const TypeModel = defineComponent({
  setup(props, {emit}) {
    let {visible, type, title} = toRefs(sysdictTypes_state.modal)
    const handle_form_finish = () => {
      visible.value = false
      type.value = ''
      getTableDatas()
    }
    return () => {
      let dynamicCom
      switch (type.value) {
        case 'addType':
          dynamicCom = <AddTypeForm onFinish={handle_form_finish}></AddTypeForm>
          break
        case 'editType':
          dynamicCom = (
            <EditTypeForm onFinish={handle_form_finish}></EditTypeForm>
          )
          break
      }
      return (
        <a-modal
          visible={visible.value}
          title={title.value}
          footer={null}
          onCancel={() => {
            handle_form_finish()
          }}
        >
          {dynamicCom}
        </a-modal>
      )
    }
  },
})

export const TypeMainViewNav = defineComponent({
  setup() {
    let {visible, type, title} = toRefs(sysdictTypes_state.modal)
    const handle_add_btn_click = () => {
      visible.value = true
      type.value = 'addType'
      title.value = '添加数据类型'
    }
    return () => (
      <div class="h-mainViewNav border-b border-default bg-white px-4 flex justify-start items-center">
        <a-button type="primary" onClick={handle_add_btn_click}>
          添加
        </a-button>
      </div>
    )
  },
})
